import time
from functools import wraps
from openai import APIError

def retry_with_backoff(tries=3, delay=1, backoff=2):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            current_try = 0
            current_delay = delay
            while current_try < tries:
                try:
                    return func(*args, **kwargs)
                except APIError as e:
                    if e.status_code == 429:  # Rate limit
                        time.sleep(current_delay)
                        current_delay *= backoff
                        current_try += 1
                    else:
                        raise
            return func(*args, **kwargs)
        return wrapper
    return decorator
